<?php

namespace App\Extension;

use Illuminate\Support\Collection;

class TreeGenerator
{
	//主键名称
	private $primaryKey;
	//父键名称
	private $parentKey;
	//级别名称
	private $levelKey;
	//传入的数组
	private $list;
	//生成的树形结构
	public $tree;

	/**
	 * TreeGenerator constructor.
	 * @param $list
	 * @param string $primaryKey
	 * @param string $parentKey
	 * @param string $levelKey
	 */
	function __construct($list, $primaryKey = 'id', $parentKey = 'parent_id', $levelKey = 'level')
	{
		$this->list = $list;
		$this->primaryKey = $primaryKey;
		$this->parentKey = $parentKey;
		$this->levelKey = $levelKey;
		$this->tree = array();
		$this->make();
	}

	/**
	 * 生成树结构
	 *
	 * Date: 2018/1/29
	 * @author George
	 * @return bool|string
	 */
	private function make()
	{
		if ($this->list instanceof Collection) {
			$list = $this->list->sortBy($this->primaryKey)->groupBy($this->parentKey);
		} else {
			$list = collect($this->list)->sortBy($this->primaryKey)->groupBy($this->parentKey);
		}

		$this->tree = $list->pull($this->levelKey);

		foreach ($this->tree as $item) {
			$children = $list->pull($item->{$this->primaryKey});

			if ($children) {
				$item->children = $children;
			}
		}
	}
}
